<template>
  <view class="personalInfor-page">
    <head-box></head-box>

    <view class="personalInfor-page-main">
      <view class="personalInfor-page-main-box">
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>头像</text></view>
          <view class="_main-item-chunk _main-item-val" @tap="changeHead">
            <view class="_main-item-val-head"
            ><image class="head-img" :src="headUrl" mode=""></image
            ></view>
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>昵称</text></view>
          <view class="_main-item-chunk _main-item-val">
            <input
                cursorSpacing="10"
                class="_main-item-val-input"
                type="text"
                placeholder="请输入昵称"
                v-model="userNickname"
            />
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>姓名</text></view>
          <view class="_main-item-chunk _main-item-val">
            <input
                cursorSpacing="10"
                class="_main-item-val-input"
                type="text"
                placeholder="请输入姓名"
                v-model="userPname"
            />
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>证件号</text></view>
          <view class="_main-item-chunk _main-item-val">
            <input
                maxlength="18"
                cursorSpacing="10"
                class="_main-item-val-input"
                @blur="idCardBlur"
                type="text"
                v-model="idCardNumFilter"
                placeholder="请输入证件号"
            />
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>年龄</text></view>
          <view class="_main-item-chunk _main-item-val">
            <text>{{ ageNum }}</text>
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>性别</text></view>
          <view class="_main-item-chunk _main-item-val">
            <text>{{ sexType }}</text>
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>手机号</text></view>
          <view class="_main-item-chunk _main-item-val">
            <text>{{ userPhoneFilter }}</text>
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item" style="display: none">
          <view class="_main-item-chunk _main-item-label"><text>年收入</text></view>
          <view class="_main-item-chunk _main-item-val">
            <picker
                class="_main-item-val-input"
                @change="incomePicker"
                :value="incomeIndex"
                :range="incomeArr"
            >
              <view class="uni-input _main-item-val-input-text">
                {{ incomeArr[incomeIndex] }}
                <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
              </view>
            </picker>
          </view>
        </view>
        <!-- <view class="_main-item">
					<view class="_main-item-chunk _main-item-label"><text>是否离异</text></view>
					<view class="_main-item-chunk _main-item-val">
						<picker class="_main-item-val-input" @change="handlePicker" :value="isIndex" :range="isArr">
							<view class="uni-input _main-item-val-input-text">
								{{isArr[isIndex]}}
								<image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
							</view>
						</picker>
					</view>
				</view> -->
        <view class="_main-item" style="display: none">
          <view class="_main-item-chunk _main-item-label"><text>学历</text></view>
          <view class="_main-item-chunk _main-item-val">
            <picker
                class="_main-item-val-input"
                @change="handlePicker2"
                :value="isIndex2"
                :range="isArr2"
            >
              <view class="uni-input _main-item-val-input-text">
                {{ isArr2[isIndex2] }}
                <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
              </view>
            </picker>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>职业</text></view>
          <view class="_main-item-chunk _main-item-val">
            <input
                cursorSpacing="10"
                class="_main-item-val-input"
                type="text"
                v-model="jobType"
                placeholder="请输入职业"
            />
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>地区</text></view>
          <view class="add" @click="onAddShow" >{{add.value || '请选择市'}}
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
          <view class="add" @click="onAReaShow" v-if="add.value.length">{{area.value || '请选择区'}}
            <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
          </view>
        </view>
        <view class="_main-item">
          <view class="_main-item-chunk _main-item-label"><text>详情地址</text></view>
          <u-input v-model="address"
                   type="textarea"
                   maxlength="255"
                   :placeholder="area.value.length?`请输入详情地址`:'选择完区后再输入详情地址'"
          :disabled="!area.value.length"
          />
        </view>
        <view class="_main-item" style="display: none">
          <view class="_main-item-chunk _main-item-label"><text>是否有房</text></view>
          <view class="_main-item-chunk _main-item-val">
            <picker
                class="_main-item-val-input"
                @change="handlePicker3"
                :value="isIndex3"
                :range="isArr3"
            >
              <view class="uni-input _main-item-val-input-text">
                {{ isArr3[isIndex3] }}
                <image class="drop-dowm-img" src="../../static/img/drop-down.png" mode=""></image>
              </view>
            </picker>
          </view>
        </view>

        <view class="save-btn" @tap="saveData">
          <view class="save-btn-text"><text>保存</text></view>
        </view>
      </view>
    </view>
    <image-cropper :src="tempFilePath" @confirm="confirm" @cancel="cancel"></image-cropper>
    <u-select v-model="add.show" :list="add.list"
              :default-value="add.index"
    @confirm="onAddConfirm"
    ></u-select>
    <u-select v-model="area.show" :list="area.list"
              :default-value="area.index"
              @confirm="onAreaConfirm"
    ></u-select>
    <tabs-box></tabs-box>
  </view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { gpUserEdit, gpUserInfo } from '@/common/request.js'
import ImageCropper from '@/components/invinbg-image-cropper/invinbg-image-cropper.vue'
// 以下路径需根据项目实际情况填写
import { pathToBase64 } from '@/js_sdk/mmmm-image-tools/index.js'
//import {isIdCard} from '@/common/functions.js';
import { identityCodeValid } from '@/common/validateIdent.js'
import {base64Uploads,wwwApplication} from '@/common/variable'
import { asterisk } from '@/common/base'
import {getDictItemstList} from '@/api/dict'
export default {
  data() {
    return {
      //市
      add:{
        show:false,//下拉菜单展示
        list:[],//列表
        value:'',//值
        id:'',//id
        index:[0],//第几项
      },
      //区
      area:{
        show:false,//下拉菜单展示
        list:[],//列表
        value:'',//值
        id:'',//id
        index:[0],//第几项
      },
      address:'',//详情地址
      userPhone: '',
      userNickname: '',
      userPname: '',
      phone: '',//手机号
      headUrl: require('../../static/img/logob.png'),
      tempFilePath: '',
      idCardNum: '',
      idCard: '',//身份证
      ageNum: '',
      sexType: '',
      jobType: '',
      incomeIndex: 0,
      incomeArr: ['1-20万', '20-50万', '50-100万'],
      isIndex: 0,
      isArr: ['否', '是'],
      isIndex2: 0,
      isArr2: ['研究生', '本科', '专科', '高中', '初中', '小学'],
      isIndex3: 0,
      isArr3: ['是', '否'],
    }
  },
  filters: {},
  computed: {
    ...mapState([ 'userInfo', 'token']),
    //身份证号
    idCardNumFilter:{
      get(){
        if(!this.idCardNum.length){
          return ''
        }
        return asterisk(this.idCardNum, 6, 8, 14)
      },
      set(v){
        this.idCard = v
        return asterisk(v, 6, 8, 14)
      }

    },
    //手机号
    userPhoneFilter:{
      get(){
        if(!this.userPhone.length){
          return ''
        }
        return asterisk(this.userPhone, 3, 4, 7)
      },
      set(v){
        this.phone = v
        return asterisk(v, 3, 4, 7)
      }
    },
  },
  onLoad() {
    this.getDistrict({"column": "sorting","order": "desc",dictCode:'new_area_code'})
    if (!uni.getStorageSync('token')) {
      uni.navigateTo({
        url: '../login/login',
      })
      return
    }
    gpUserInfo().then((res) => {
      if (res.success) {
        this.saveUserInfo(res.result, this.token)
        this.userPname = this.userInfo.userPname
        this.phone = this.userInfo.userPhone
        this.idCard = this.userInfo.userPid
        ;(this.userNickname = this.userInfo.userNickname),
            (this.idCardNum = this.userInfo.userPid)
        this.idCardBlur()
        this.userPhone = this.userInfo.userPhone
        this.incomeIndex = this.userInfo.userIncome
        this.isIndex2 = this.userInfo.userEducation
        this.isIndex3 = this.userInfo.userHashouse
        this.jobType = this.userInfo.userCareer
        this.headUrl = this.userInfo.userPic
        this.address = this.userInfo.address
        // this.area.id = this.userInfo.streetCode
        this.getDictAdd()
        // this.getDictAdd('area','streetCode')
      }
    })
    if (this.idCardNum) this.idCardBlur()
  },
  components: { ImageCropper },
  onShow(){
    // #ifdef H5
    console.log('分享')
    this.$wxSetShare()
    // #endif
  },
  methods: {
    ...mapMutations(['saveUserInfo']),
    //查询市
    //'add','areaCode'
    getDictAdd(){
      const list = this.add.list
      const index= list.findIndex(item=>{
        return item.value===this.userInfo.areaCode
      })
      this.add.index=[index]
      if(this.add&&this.add.list[index]){
        const {label,value} =this.add.list[index]
        this.add.id=value
        this.add.value=label
        if(this.add.id){
          this.getAddRessDistrict(this.add.id,2)
        }
      }

    },
    //复合
    onConfirmData(data,arr){
      const {value,label} =data[0]
      this[arr].value =label
      this[arr].id =value
      const index= this[arr].list.findIndex(item=>{
        return item.value===value
      })
      this[arr].index=[index]
    },
    //市
    onAddConfirm(data){
      this.onConfirmData(data,'add')
      this.area.index = [0]
      this.area.value=''
      this.area.id=''
      this.getAddRessDistrict(data[0].value)
    },
    onAddShow(){
      this.add.show=true
    },
    //区
    onAreaConfirm(data){
      this.onConfirmData(data,'area')
    },
    onAReaShow(){
      this.area.show=true
    },
    //市区
    getDistrict(params){
      const list = []
      getDictItemstList(params).then(res => {
            const  {code, result} = res
            if(code===0 || code === 200) {
              result.map ( item => {
                const {
                  title ,
                  value
                } = item
                list.push ( {
                  label : title , value ,
                } )
              } )
            }
       this.add.list = list
        this.add.value=list[0].label
        this.add.id=list[0].value
        this. getAddRessDistrict(list[0].value)
      })
    },
    //区
    getAddRessDistrict(dictCode,type){
      const params =  {column: "sorting",order: "desc",dictCode}
      const list = []
      getDictItemstList(params).then(res => {
        const  {code, result} = res
        if(code===0 || code === 200) {
          result.map ( item => {
            const {
              title ,
              value
            } = item
            list.push ( {
              label : title , value ,
            } )
          } )
        }
        this.area.list = list
        if(type===2){
          const list = this.area.list
          const index= list.findIndex(item=>{
            return item.value===this.userInfo.streetCode
          })
          this.area.index=[index]
          const {label,value} =this.area.list[index]
          this.area.id=value
          this.area.value=label
        }
      })
    },
    saveData() {
      var that = this
      that.idCard = that.idCard.toUpperCase()
      if (!this.userNickname.length || !this.userNickname.trim()) {
        this.$api.msg('请输入昵称')
        return
      }
      if (!this.idCard.length || !identityCodeValid(this.idCard)) {
        this.$api.msg('必须输入正确的身份证信息')
        return
      }
      var params = {
        userNickname: that.userNickname,
        userPname: that.userPname,
        userPid: that.idCard,
        userIncome: that.incomeIndex,
        userEducation: that.isIndex2,
        userHashouse: that.isIndex3,
        userCareer: that.jobType,
        userPic: that.headUrl,
        areaCode:this.add.id,
        streetCode:this.area.id,
        address:this.address
      }
      gpUserEdit(params).then((res) => {
        if (res.success) {
          this.$api.msg('编辑成功')
          params['userPhone'] = that.userPhone
          this.saveUserInfo(params, this.token)
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        }
      })
    },
    toBack() {
      uni.navigateBack({
        delta: 1,
      })
    },
    changeHead() {
      const _this = this
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: function (res) {
          _this.tempFilePath = res.tempFilePaths.shift()
        },
      })
    },
    confirm(e) {
      var that = this
      this.tempFilePath = ''
      this.cropFilePath = e.detail.tempFilePath
      const token = uni.getStorageSync('token')
      const header = {}
      header['content-type'] =
          wwwApplication
      header['X-Access-Token'] = token
      pathToBase64(this.cropFilePath).then((base64) => {
        const url = base64Uploads
        uni.request({
          url: url, //仅为示例，非真实的接口地址
          data: {
            fileStr: 'personalInfor.jpg,' + base64,
          },
          method: 'post',
          header: header,
          success: (res) => {
            res = res.data
            if (res.success) {
              that.headUrl = process.uniEnv.BASE_API + '/gp-boot/sys/common/static/' + res.message
            }
          },
        })
      })
    },
    cancel() {
      console.log('canceled')
    },
    incomePicker(e) {
      // console.log('picker发送选择改变，携带值为', e.target.value)
      this.incomeIndex = e.target.value
    },
    handlePicker(e) {
      this.isIndex = e.target.value
    },
    handlePicker2(e) {
      this.isIndex2 = e.target.value
    },
    handlePicker3(e) {
      this.isIndex3 = e.target.value
    },
    idCardBlur() {
      const _data = this.analyzeIDCard(this.idCardNum)
      this.ageNum = _data.age
      this.sexType = _data.sex
    },
    analyzeIDCard(IDCard) {
      const sexAndAge = {}
      //获取用户身份证号码
      const userCard = IDCard
      //如果身份证号码为undefind则返回空
      if (!userCard) {
        return sexAndAge
      }
      //获取性别
      if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
        sexAndAge.sex = '男'
      } else {
        sexAndAge.sex = '女'
      }
      //获取出生年月日
      //userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
      const yearBirth = userCard.substring(6, 10)
      const monthBirth = userCard.substring(10, 12)
      const dayBirth = userCard.substring(12, 14)
      //获取当前年月日并计算年龄
      const myDate = new Date()
      const monthNow = myDate.getMonth() + 1
      const dayNow = myDate.getDay()
      let age = myDate.getFullYear() - yearBirth
      if (monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)) {
        age--
      }
      //得到年龄
      sexAndAge.age = age
      //返回性别和年龄
      return sexAndAge
    },
  },
}
</script>

<style lang="scss" scoped>
.personalInfor-page {
  width: 100%;
  box-sizing: border-box;
  padding-bottom: 200rpx;
  .top-fixed {
    position: fixed;
    top: 0;
    z-index: 1;
  }
  .top {
    width: 100%;
    height: 100rpx;
    padding: 0 30rpx;
    // background-color: #007AFF;
    background-color: #f7f7f7;
    box-shadow: 0 1px 6rpx #ccc;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    .top-text {
      color: #000;
      font-size: 34rpx;
    }
  }
  .top-box {
    width: 100%;
    height: 100%;
    position: relative;
    text-align: center;
    line-height: 100rpx;
    .back-img {
      width: 44rpx;
      height: 40rpx;
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      margin: auto;
      margin-left: 0rpx;
    }
  }
  .personalInfor-page-main {
    width: 100%;
    padding: 0 50rpx;
    box-sizing: border-box;
    .personalInfor-page-main-box {
      width: 100%;
      ._main-item {
        // height: 86rpx;
        border-bottom: 1px solid rgba(200, 199, 204, 0.5);
        display: flex;
        flex-wrap: nowrap;
        justify-content: space-between;
        align-items: center;
        ._main-item-chunk {
          font-size: 34rpx;
          color: #000;
          line-height: 84rpx;
        }
        ._main-item-label {
          width: 30%;
        }
        ._main-item-val {
          width: 70%;
          display: flex;
          flex-wrap: nowrap;
          justify-content: flex-end;
          align-items: center;
          ._main-item-val-head {
            width: 48rpx;
            height: 48rpx;
            border-radius: 50%;
            display: flex;
            .head-img {
              width: 100%;
              height: 100%;
              border-radius: 50%;
            }
          }
          ._main-item-val-input {
            text-align: right;
            display: flex;
            ._main-item-val-input-text {
              display: flex;
              flex-wrap: nowrap;
              align-items: center;
            }
            .drop-dowm-img {
              width: 30rpx;
              height: 30rpx;
              margin-left: 10rpx;
              transform: rotateZ(270deg);
            }
          }

        }
      }
      .save-btn {
        width: 100%;
        text-align: center;
        margin-top: 60rpx;
      }
      .save-btn-text {
        width: 50%;
        font-size: 28rpx;
        font-weight: 400;
        line-height: 1.42;
        position: relative;
        display: inline-block;
        margin-bottom: 0;
        padding: 12rpx 24rpx;
        cursor: pointer;
        -webkit-transition: all;
        transition: all;
        -webkit-transition-timing-function: linear;
        transition-timing-function: linear;
        -webkit-transition-duration: 0.2s;
        transition-duration: 0.2s;
        text-align: center;
        vertical-align: top;
        white-space: nowrap;
        border-radius: 6rpx;
        border-top-left-radius: 6rpx;
        border-top-right-radius: 6rpx;
        border-bottom-right-radius: 6rpx;
        border-bottom-left-radius: 6rpx;
        background-clip: padding-box;
        color: #fff;
        border: 1px solid #007aff;
        background-color: #007aff;
      }
    }
  }
}
.drop-dowm-img {
  vertical-align: middle;
  width: 30rpx;
  height: 30rpx;
  margin-left: 10rpx;
  transform: rotateZ(270deg);
}
</style>

